package com.heer.gymnasium.module.team.views;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.module.evaluate.beans.EvaTagBean;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.main.beans.CategoryBean;
import com.heer.gymnasium.module.main.views.MainActivity;
import com.heer.gymnasium.module.team.beans.TeamDetailBean;
import com.heer.gymnasium.module.team.beans.TeamResponseBean;
import com.heer.gymnasium.util.ImageUtil;
import com.heer.imagepick.DensityUtils;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * 创建战队
 * Created by zy on 2018/3/1.
 */

public class CreateTeamActivity extends BaseActivity {
    private final static int RES_ID_ROOT = R.layout.layout_create_team;
    private final static int RES_ID_TYPE_SP = R.id.layout_create_team_type_sp;
    private final static int RES_ID_ADD_LOGO_RL = R.id.layout_create_team_add_logo_rl;
    private final static int RES_ID_LOGO_IV = R.id.layout_create_team_logo_iv;
    private final static int RES_ID_LOGO_PANEL = R.id.layout_create_team_logo_ll;
    private final static int RES_ID_DELETE = R.id.layout_create_team_delete_current_iv;
    private final static int RES_ID_ADD_SUBMIT_TV = R.id.layout_create_team_submit_tv;
    private final static int RES_ID_ADD_NAME_ET = R.id.layout_create_team_name_et;
    private final static int RES_ID_ADD_DECLARE_ET = R.id.layout_create_team_declare_et;
    private final static int RES_ID_LABEL = R.id.layout_create_team_label_tfl;

    private static final int RES_ID_ITEM_SPINNER_LAYOUT = R.layout.item_dropdown;
    private static final int RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT = android.R.layout.simple_dropdown_item_1line;
    private static final int RES_ID_ITEM_SPINNER_TV = R.id.item_dropdown_type_tv;

    private final String DEFAULT_SPORT_TYPE = "请选择战队类型";
    private static final int REQUEST_CODE_PICK_IMAGE = 2;

    @BindView(RES_ID_TYPE_SP)
    Spinner typeSpinner;
    @BindView(RES_ID_ADD_LOGO_RL)
    View vAddLogo;
    @BindView(RES_ID_ADD_NAME_ET)
    EditText etName;
    @BindView(RES_ID_ADD_DECLARE_ET)
    EditText etDeclare;
    @BindView(RES_ID_LOGO_IV)
    ImageView ivLogo;
    @BindView(RES_ID_LOGO_PANEL)
    View vLogoPanel;
    @BindView(RES_ID_LABEL)
    TagFlowLayout tflLabel;
    @BindView(RES_ID_ADD_SUBMIT_TV)
    TextView tvSubmit;

    private ArrayAdapter<CategoryBean> typeAdapter;
    private List<CategoryBean> typeList;
    private File currentPic;
    private TagAdapter<EvaTagBean> tagAdapter;
    private List<EvaTagBean> tagList;
    private int d5, d10;
    private Handler mHandler;
    private boolean categoryOk = false, tagOk = false;
    private String tid;
    private boolean isInit = true;

    private CreateTeamActivity $this;

    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(RES_ID_ROOT);
        typeList = new ArrayList<>();
        tagList = new ArrayList<>();
        d5 = DensityUtils.dip2px($this, 5);
        d10 = d5 * 2;
        CategoryBean defaultCategory = new CategoryBean();
        defaultCategory.setTitle(DEFAULT_SPORT_TYPE);
        typeList.add(defaultCategory);
        tid = getIntent().getStringExtra(EXTRA_ID);
        typeAdapter = new ArrayAdapter<CategoryBean>(this, RES_ID_ITEM_SPINNER_LAYOUT, typeList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = getLayoutInflater().inflate(RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT, null);
                TextView tv = (TextView) convertView;
                tv.setText(getItem(position).getTitle());
                LinearLayout view = new LinearLayout($this);
                view.addView(convertView);
                view.setOrientation(LinearLayout.VERTICAL);
                ImageView imageView = new ImageView($this);
                imageView.setBackgroundResource(R.color.bg_color);
                imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
                view.addView(imageView);
                view.setPadding(10, 10, 10, 10);
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = getLayoutInflater().inflate(RES_ID_ITEM_SPINNER_LAYOUT, null);
                TextView tv = (TextView) convertView.findViewById(RES_ID_ITEM_SPINNER_TV);
                tv.setText(getItem(position).getTitle());
                return convertView;
            }
        };
        typeAdapter.setDropDownViewResource(RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT);

        tagAdapter = new TagAdapter<EvaTagBean>(tagList) {
            @Override
            public View getView(FlowLayout parent, int position, EvaTagBean evaTagBean) {
                TextView textView = new TextView($this);
                textView.setText(evaTagBean.getName());
                if (evaTagBean.isSelect()) {
                    textView.setTextColor(getResources().getColor(R.color.white));
                    textView.setBackgroundResource(R.drawable.yellow_button_bg);
                } else {
                    textView.setTextColor(getResources().getColor(R.color.black));
                    textView.setBackgroundResource(R.drawable.white_corner_bg);
                }
                textView.setPadding(d10, d5, d10, d5);
                return textView;
            }
        };

        mHandler = new Handler() {
            @Override
            public void dispatchMessage(Message msg) {
                super.dispatchMessage(msg);
                if (!TextUtils.isEmpty(tid) && categoryOk && tagOk) {
                    categoryOk = false;
                    tagOk = false;
                    getCorpsInfo();
                }
            }
        };
    }

    @Override
    protected void initView() {
        super.initView();
        if (TextUtils.isEmpty(tid)) {
            titleUtils.setTitleText("创建战队");
            tvSubmit.setText("创建战队");
        } else {
            titleUtils.setTitleText("编辑战队");
            tvSubmit.setText("编辑战队");
        }
        titleUtils.startMainActivity(this);
        typeSpinner.setAdapter(typeAdapter);
        tflLabel.setAdapter(tagAdapter);
        tflLabel.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                if (tagList.get(position).isSelect()) {
                    tagList.get(position).setSelect(false);
                } else {
                    tagList.get(position).setSelect(true);
                }
                tagAdapter.notifyDataChanged();
                return false;
            }
        });

        //获取初始数据
        getCategoryList();
        getTagList();
    }

    final int REQUEST_CODE_CONTACT = 101;

    @OnClick(RES_ID_ADD_LOGO_RL)
    public void addLogo() {
        boolean hasPermission = true;
        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    hasPermission = false;
                }
            }
        }
        if (hasPermission) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");//相片类型
            startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
        }
    }

    @OnClick(RES_ID_DELETE)
    public void deleteCurrentPic() {
        currentPic = null;
        vAddLogo.setVisibility(View.VISIBLE);
        vLogoPanel.setVisibility(View.GONE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_CONTACT) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");//相片类型
            startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
        }
    }

    @OnClick(RES_ID_ADD_SUBMIT_TV)
    public void doSubmit() {
        StringBuffer tag_me = new StringBuffer();

        for (int i = 0; i < tagList.size(); i++) {
            if (tagList.get(i).isSelect()) {
                tag_me.append(tagList.get(i).getId() + ",");
            }
        }

        if (TextUtils.isEmpty(tag_me.toString())) {
            ToastUtil.show($this, "暂无选择评价标签");
            return;
        } else {
            tag_me.delete(tag_me.length() - 1, tag_me.length());
        }

        SignHelper signHelper = new SignHelper("");

        if (TextUtils.isEmpty(tid)) {
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), currentPic);
            mAppHelper.apiService().addCorps(
                    toRequestBody(signHelper.GetParameter("key"))
                    , toRequestBody(signHelper.getToken())
                    , toRequestBody(signHelper.GetParameter("unixtime"))
                    , toRequestBody(etName.getText().toString())
                    , toRequestBody(((CategoryBean) typeSpinner.getSelectedItem()).getId())
                    , toRequestBody(etDeclare.getText().toString())
                    , toRequestBody(tag_me.toString())
                    , requestFile
            ).enqueue(new BaseCallback<ApiResponse<Object>>() {
                @Override
                public void onSuccess(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                    ToastUtil.show($this, response.message());
                    setResult(RESULT_OK);
                    finish();
                }
            });
        } else {
            RequestBody requestFile = null;
            if (currentPic == null) {
                toRequestBody("");
            } else {
                requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), currentPic);
            }

            mAppHelper.apiService().saveCorps(
                    toRequestBody(signHelper.GetParameter("key"))
                    , toRequestBody(signHelper.getToken())
                    , toRequestBody(signHelper.GetParameter("unixtime"))
                    , toRequestBody(tid)
                    , toRequestBody(etName.getText().toString())
                    , toRequestBody(((CategoryBean) typeSpinner.getSelectedItem()).getId())
                    , toRequestBody(etDeclare.getText().toString())
                    , toRequestBody(tag_me.toString())
                    , requestFile
            ).enqueue(new BaseCallback<ApiResponse<Object>>() {
                @Override
                public void onSuccess(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                    ToastUtil.show($this, response.message());
                    setResult(RESULT_OK);
                    finish();
                }
            });
        }

    }

    private RequestBody toRequestBody(String param) {
        return RequestBody.create(MediaType.parse("multipart/form-data"), param);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            if (data == null) {
                vAddLogo.setVisibility(View.VISIBLE);
                vLogoPanel.setVisibility(View.GONE);
                return;
            } else {
                vAddLogo.setVisibility(View.GONE);
                vLogoPanel.setVisibility(View.VISIBLE);
            }

            Uri uri = data.getData();
            currentPic = uri2File(uri);

            try {
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                ivLogo.setImageBitmap(bitmap);
                ivLogo.setTag(COMMON_ID_TAG, uri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                vAddLogo.setVisibility(View.VISIBLE);
                vLogoPanel.setVisibility(View.GONE);
                ToastUtil.show($this, "读取文件失败");
            }
        }
    }

    private File uri2File(Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null,
                null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    private void getCategoryList() {
        mAppHelper.apiService().getCategoryList("").enqueue(new BaseCallback<ApiResponse<List<CategoryBean>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<CategoryBean>>> call, Response<ApiResponse<List<CategoryBean>>> response) {
                typeList.clear();
                CategoryBean defaultCategory = new CategoryBean();
                defaultCategory.setTitle(DEFAULT_SPORT_TYPE);
                typeList.add(defaultCategory);
                typeList.addAll(response.body().getData());
                typeAdapter.notifyDataSetChanged();
                categoryOk = true;
                mHandler.sendEmptyMessage(0);
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    private void getTagList() {
        mAppHelper.apiService().getTagList(Type.TAG_TEAM).enqueue(new BaseCallback<ApiResponse<List<EvaTagBean>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<EvaTagBean>>> call, Response<ApiResponse<List<EvaTagBean>>> response) {
                tagList.addAll(response.body().getData());
                tagAdapter.notifyDataChanged();
                tagOk = true;
                mHandler.sendEmptyMessage(0);
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    private void getCorpsInfo() {
        mAppHelper.apiService().getCorpsInfo(tid).enqueue(new BaseCallback<ApiResponse<TeamResponseBean.Info>>() {
            @Override
            public void onSuccess(Call<ApiResponse<TeamResponseBean.Info>> call, Response<ApiResponse<TeamResponseBean.Info>> response) {
                TeamDetailBean bean = TeamDetailBean.dataChange(response.body().getData());
                int index = 0;
                for (CategoryBean item : typeList) {
                    if (TextUtils.equals(item.getId(), bean.getCatogeryId())) {
                        typeSpinner.setSelection(index);
                        break;
                    }
                    index++;
                }
                etName.setText(bean.getName());
                etDeclare.setText(bean.getManifesto());
                ImageUtil.loadUrl($this, bean.getIconUrl(), DRAWABLE_DEFAULT_LOGO, ivLogo);
                vLogoPanel.setVisibility(View.VISIBLE);
                vAddLogo.setVisibility(View.GONE);

                List<String> tag_me = bean.getMyTags();
                if (tag_me != null) {
                    for (EvaTagBean item : tagList) {
                        for (String tag : tag_me) {
                            if (TextUtils.equals(item.getName(), tag)) {
                                item.setSelect(true);
                                break;
                            } else {
                                item.setSelect(false);
                            }
                        }
                    }
                }

                tagAdapter.notifyDataChanged();
            }
        });
    }

    /**
     * 创建战队
     *
     * @param context
     * @param requestCode
     */
    public static void startActivity(Activity context, int requestCode) {
        Intent mIntent = new Intent(context, CreateTeamActivity.class);
        context.startActivityForResult(mIntent, requestCode);
    }

    /**
     * 编辑战队
     *
     * @param context
     * @param requestCode
     * @param tid
     */
    public static void startActivity(Activity context, int requestCode, String tid) {
        Intent mIntent = new Intent(context, CreateTeamActivity.class);
        mIntent.putExtra(EXTRA_ID, tid);
        context.startActivityForResult(mIntent, requestCode);
    }
}
